<template>
	<view class="grace-body">
		<fu-custom bgColor="bg-white" :isBack="true" :isBottom="true">
			<block slot="content">{{i18n['我的资料']}}</block>
		</fu-custom>
		<!-- 个人资料表单 start -->
		<form @submit="formSubmit" class="grace-form grace-margin-top">
			<!-- 顶部头像模块 start -->
			<view class="head_list cu-list menu">
				<view class="cu-item">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">{{i18n['头像']}}</text>
						<view class="width-100 height-100">
							<image class="width-100 height-100 round" :src="head_img || 'https://heart.jujiaxindongli.cn/newimage/logo.jpg'"
								mode="widthFix" @tap="openImg('headerimg')"></image>
						</view>
					</view>
				</view>
			</view>
			<!-- 顶部头像模块 end -->
			<view class="cu-list menu ">
				<view class="cu-item">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">ID</text>
						<text class=" text-lg text-666 text-right">{{user_id}}</text>
					</view>
				</view>
				<!-- 昵称 start -->
				<view class="cu-item ">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">{{i18n['昵称']}}</text>
						<input type="text" :selection-start="user_name.length" :selection-end="user_name.length"
							:cursor="user_name.length" class="input text-lg text-666" name="user_nickname"
							maxlength="10" :auto-blur="true" v-model="user_nickname" :placeholder="i18n['请输入昵称']"
							style="text-align: right" />
					</view>
				</view>
				<!-- 昵称 end -->

				<!-- 性别 start -->
				<view class="cu-item">
					<view class="content flex justify-between align-center" @click="toggleTab('selector')">
						<text class="title text-lg text-333">{{i18n['性别']}}</text>
						<text class="text-666">{{ sexName }}</text>
					</view>
				</view>
				<!-- 性别 end -->

				<!-- 生日 start -->
				<view class="cu-item solid-bottom">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">{{i18n['生日']}}</text>
						<view class="text-lg text-666 text-cut-2 text-right" @tap="toggleTab('date')">
							<view :class="name == i18n['点击选择'] ? '' : 'address-select'">{{ dateValue }}</view>
						</view>
					</view>
				</view>
				<!-- 生日 end -->

				<!-- 绑定学校 start -->
				<view class="cu-item solid-bottom">
					<view class="content flex justify-between align-center" @click="handleScanCode">
						<text class="title text-lg text-333">绑定学校</text>
						<view class="text-lg text-666 text-cut-2 text-right">
							<view class="" v-if="school_name">{{school_name}}</view>
							<view class="" v-else>前往绑定</view>
						</view>
					</view>
				</view>
				<!-- 绑定学校 end -->

				<!-- 我的孩子 start -->
				<view class="cu-item solid-bottom">
					<view class="content flex justify-between align-center"
						@click="goToUrl('/pages/user/user/info/student')">
						<text class="title text-lg text-333">我的孩子</text>
						<view class="text-lg text-666 text-cut-2 text-right">
							<template v-if="students_name.length>0">
							  <text style="margin-right: 10rpx;" v-for="(item,index) in students_name" :key="index">{{item.name}}</text>
							</template>
							<template v-else>
								<view class="">绑定学生</view>
							</template>
						</view>
					</view>
				</view>
				<!-- 我的孩子 end -->

				<!-- 手机号 statr -->
				<!-- <view class="cu-item" @tap="handleJump" data-url="/pages/index/setting/verify-oldphone/index?isChange=1">
          <view class="content flex justify-between align-center">
            <text class="title text-lg text-333">{{i18n['手机号']}}</text>
            <input type="text" class="input text-666 text-lg" name="mobile" maxlength="11" v-model="mobile"
              disabled="" :placeholder="i18n['请输入昵称']" style="text-align: right" />
          </view>
        </view> -->
				<!-- 手机号 end -->

				<!-- 邮箱 start -->
				<!-- <view class="cu-item">
          <view class="content flex justify-between align-center">
            <text class="title text-lg text-333">{{i18n['邮箱']}}</text>
            <input type="text" class="input text-666 text-lg" name="user_email" v-model="user_email"
              :placeholder="i18n['请绑定邮箱']" style="text-align: right" />
          </view>
        </view> -->
				<!-- 邮箱 end -->

				<!-- 所在地 start -->
				<!-- <view class="cu-item">
          <view class="content flex justify-between align-center">
            <text class="title text-lg text-333 address">{{i18n['所在地']}}</text>
            <view class="text-lg text-666 text-cut-2 text-right" @tap="toggleTab('region')">
              <view :class="name == i18n['点击选择'] ? '' : 'address-select'">{{
                name
                }}</view>
            </view>
          </view>
        </view> -->
				<!-- 所在地 end -->
			</view>
		</form>
		<!-- 个人资料表单 end -->
		<!-- 选择城市 start -->
		<w-picker :visible.sync="cityVisible" mode="region" :value="defaultVal" themeColor="#FF6F27"
			default-type="value" :hide-area="false" @confirm="onConfirm($event, 'region')" ref="region"></w-picker>
		<!-- 选择城市 end -->
		<!-- 选择生日 start -->
		<view class="birthday-wrap">
			<w-picker :visible.sync="timeVisible" mode="date" fields="day" :value="dateValue" themeColor="#FF6F27"
				:disabled-after="true" @confirm="onConfirm($event, 'date')" ref="date">{{i18n['选择生日']}}</w-picker>
		</view>
		<!-- 选择生日 end -->
		<!-- 选择性别 start -->
		<view class="sex-wrap">
			<w-picker :visible.sync="visible" mode="selector" :value="sexName" default-type="name" themeColor="#FF6F27"
				:default-props="defaultProps" :options="sex" @confirm="onConfirm($event,'selector')" ref="selector">
				{{i18n['选择性别']}}</w-picker>
		</view>
		<!-- 选择性别 end -->
		<!-- 头像start -->
		<fu-popup ref="headerimg" v-model="headerShow" borderRadius="16" :safeAreaInsetBottom="true" mode="bottom">
			<view class="header-popup text-333 text-weight-400 text-lg text-center">
				<view class="header-100" @click="chooseImage(0)">
					{{i18n['修改头像']}}
				</view>
				<view class="header-100 solid-top" @click="chooseImage(1)">
					{{i18n['拍照']}}
				</view>
				<view class="header-100 solid-top" @click="chooseImage(2)">
					{{i18n['从手机相册选择']}}
				</view>
				<view class="height-20"></view>
				<view class="header-100 " style="color: #FF6F27;" @click="closeImg('headerimg')">
					{{i18n['取消']}}
				</view>
			</view>
		</fu-popup>
		<!-- 头像end -->
		<view class="footer">
			<view class="fu-fs32 text-bold text-center height-88 line-height-88 text-white round"
				@click="saveUserInfo()" style="background-color: #FC6A84;">{{i18n['保存']}}</view>
		</view>
		<!-- 断网检测 start -->
		<fu-notwork></fu-notwork>
		<!-- 断网检测 end -->
	</view>
</template>

<script>
	// @see 引入组件wPicker
	import wPicker from "../../components/w-picker/w-picker.vue";
	// @see 引入验证，上传图片
	import {
		UploadImage,
		validate
	} from "@/common/utils/index";
	// @let {?Fuction} timer - 保存定时器
	let timer = null;
	export default {
		components: {
			wPicker,
		},
		data() {
			return {
				isLoading: false, // {Boolean} 是否加载中
				userInfo: {}, // {Objcet} 用户信息
				head_img: "", // {String} 用户头像
				user_name: "", // {String} 用户姓名
				user_id: '',
				user_nickname: "", // {String} 用户昵称
				user_email: "", // {String} 用户邮箱
				sexIndex: 1, // {Number} 性别选项 1：男；2：女；
				sex: [{
					name: '保密',
					id: 0
				}, {
					name: global.i18n["男"],
					id: 1
				}, {
					name: global.i18n["女"],
					id: 2
				}], // {Array} 性别数组
				defaultProps: {
					"label": "name",
					"value": "id"
				},
				dateValue: global.i18n["请选择生日"], // {String} 生日默认显示
				mobile: "", // {String} 手机号码
				name: global.i18n["点击选择"], // {String} 所在地默认选择
				mode: "region", // {String} 组件wPicker的类型
				defaultVal: [1, 0, 0], // {Array} 城市编码
				city1: [], // {Array} 对应的省市区
				thumb: global.SYSTEM_CONFIG.logo, // {String} 默认图片
				cityVisible: false, // {Boolean} 组件wPicker是否显示
				isCanSave: false, // 是否可以保存
				form: {
					user_nickname: "",
					user_name: "",
					user_email: "",
					sexIndex: "",
					dateValue: "",
					defaultVal: "",
				}, // 旧数据，用来判断是否修改
				timeVisible: false, //时间组件
				visible: false, //性别组件
				headerShow: false,
				addFalg: false, //防连点
				school_id:'', // 学校id
				school_name:'', // 学校姓名
				students_name:[], // 学生名称
			};
		},
		computed: {
			sexName() {
				let name = this.sex[this.sexIndex].name;
				console.log('this.sexIndex', name);
				return name;
			}
		},
		watch: {
			user_nickname(val) {
				console.log(val, this.form.user_nickname, this.form.user_nickname == val);
				if (val != this.form.user_nickname) {
					this.isCanSave = true;
				}
			},
			user_email(val) {
				console.log(val, this.form);
				if (val != this.form.user_email) {
					this.isCanSave = true;
				}
			},
			sexIndex(val) {
				console.log(val, this.form);
				if (val != this.form.sexIndex) {
					this.isCanSave = true;
				}
			},
			dateValue(val) {
				console.log(val, this.form);
				if (val != this.form.dateValue) {
					this.isCanSave = true;
				}
			},
			defaultVal(val) {
				console.log(val, this.form);
				if (String(val) != String(this.form.defaultVal)) {
					this.isCanSave = true;
				}
			},
		},
		onLoad(option) {
			// 创建一个变量 userInfo ，把全局的用户信息浅拷贝到 userInfo
			let userInfo = Object.assign({}, global.userInfo);
			this.userInfo = userInfo;
			this.head_img = userInfo.head_img ? userInfo.head_img : "";
			this.user_nickname = userInfo.user_nickname;
			this.user_name = userInfo.user_name;
			this.user_email = userInfo.user_email;
			this.user_id = userInfo.id
			this.sexIndex = userInfo.sex ? userInfo.sex : 0;
			// 用户的生日信息，有的话就放到全局方法里过滤一下，没有显示默认
			this.dateValue = userInfo.birthday ? userInfo.birthday : this.i18n["请选择生日"];
			this.mobile = userInfo.mobile;
			this.name = userInfo.address ? userInfo.address : this.i18n["点击选择"];
			this.defaultVal = userInfo.address ?
				userInfo.address_code.split(",") : [1, 0, 0];

			// 保存旧数据
			this.form.user_nickname = this.user_nickname;
			this.form.user_email = this.user_email;
			this.form.sexIndex = this.sexIndex;
			this.form.dateValue = this.dateValue;
			this.form.defaultVal = this.defaultVal;
			/**
			 * @description 监听手机号修改事件
			 */
			uni.$on("changeMobile", (data) => {
				var mobile = data.substr(0, 3) + "****" + data.substr(7);
				this.mobile = mobile;
			});
			/**
			 * @description 监听监听上传头像事件
			 */
			uni.$on("uPicCropper", (path) => {
				this.uploadUserImg(path);
			});
		},
		onShow() {
			this.getBindStudent()
			this.getInfo()
		},
		onUnload() {
			// 关闭当前页面的监听事件
			uni.$off("uPicCropper");
			uni.$off("changeMobile");
		},
		methods: {
			// 获取用户信息
			getInfo() {
				this.$api.post(global.apiUrls.postGetUserInfo).then(res => {
					if (res.data.code == 1) {
					    this.school_name =  res.data.data.school_name
						console.log(res.data.data)
						console.log(res.data.data.school_name)
						this.$store.commit('updateUserInfo', res.data.data);
					}
				}).catch(err => {})
			},
			/**
			 * @event
			 * @description 所在地的选择弹窗显示
			 */
			// 获取绑定学生列表
			getBindStudent(){
				this.$api.post(global.apiUrls.getBindStudent).then((res)=>{
					this.students_name = res.data.data
				})
			},
			// 扫码绑定学校
			handleScanCode() {
				let that = this
				wx.scanCode({
					success: (res) => {
						console.log(res);
						if (res.result) {
							// 处理扫码结果
							console.log('扫码结果：', res.result);
							console.log(JSON.parse(res.result))
							let obj = JSON.parse(res.result)
							that.school_id = obj.id
							that.school_name = obj.name
							that.$api.post(global.apiUrls.bingSchool, {school_id:that.school_id}).then((res)=>{
								console.log(res)
								uni.showToast({
									title:res.data.msg,
									icon:'none'
								})
							})
						}
					},
					fail: function(err) {
						// uni.showToast({
						// 	title:'扫码失败，请重新扫码',
						// 	icon:'none'
						// })
					}
				});
			},
			// 跳转到绑定页面
			goToUrl(path) {
				if(!this.school_name){
					return uni.showToast({
						title:'请绑定学校'
					})
				}
				uni.navigateTo({
					url: path
				})
			},
			toggleTab(ref) {
				this.$refs[ref].show();
			},
			// 保存用户信息
			saveUserInfo() {
				if (this.addFalg) return this.$message.info("点击过快，请稍后再试")
				// 校验
				// 如果不为空的情况下使用验证方法去验证邮箱号
				if (this.user_email) {
					if (!validate(this.user_email, "email")) {
						this.$message.info(this.i18n["请输入正确的邮箱账号"]);
						return;
					}
				}
				if (!this.user_nickname.trim()) {
					this.$message.info(this.i18n["请输入昵称"]);
					return;
				}
				this.addFalg = true
				setTimeout(() => {
					this.addFalg = false
				}, 2000)

				let data = {
					user_nickname: this.user_nickname,
					sex: this.sexIndex,
					user_email: this.user_email,
					birthday: this.dateValue,
					address: this.name,
					address_code: this.defaultVal,
				};
				this.upload(data);
			},
			/**
			 * @event
			 * @description 表单上传事件
			 * @param {Object} val - 用户单独保存某一项时传进来的参数
			 */
			upload(val) {
				this.$api.post(global.apiUrls.editUserinfo, val).then((res) => {
					if (res.data.code == 1) {
						this.$store.commit('updateUserInfo', res.data.data.userinfo);
						// 更新用户信息
						this.userInfo = Object.assign({}, global.userInfo);
						this.$message.info(res.data.msg);
						// 保存旧数据
						this.form.user_nickname = this.user_nickname;
						this.form.user_email = this.user_email;
						this.form.sexIndex = this.sexIndex;
						this.form.dateValue = this.dateValue;
						this.form.defaultVal = this.defaultVal;
						// 更新保存状态
						this.isCanSave = false;
						setTimeout(() => {
							uni.navigateBack();
						}, 500);
					} else {
						this.$message.info(res.data.msg);
					}
				});
			},
			/**
			 * @event
			 * @description 性别选择事件
			 */
			bindPickerChange: function(e) {
				this.sexIndex = e.detail.value;
				if (this.userInfo.sex == this.sexIndex) return;
				// this.upload({ sex: this.sexIndex });
			},

			/**
			 * @event
			 * @description 所在地选择事件
			 * @param {Object} result - 用户所在地弹窗选择的值
			 */
			onConfirm(result, type) {
				console.log(result, type);
				if (type == 'date') {
					this.dateValue = result.value;
				}
				if (type == 'region') {
					let {
						province,
						city,
						area
					} = result.obj;
					let text = [province.label, city.label, area.label];
					let code = [province.value, city.value, area.value];
					this.name = text.join("-");
					this.city1 = text;
					this.defaultVal = code;
					if (this.userInfo.address_code == this.defaultVal || this.userInfo.address == this.name) return;
				}
				if (type == 'selector') {
					this.sexIndex = result.value;
				}
			},
			openImg(ref) {
				this.$refs[ref].open();
			},
			closeImg(ref) {
				this.$refs[ref].close();
			},
			/**
			 * @event
			 * @description 选择头像事件
			 */
			chooseImage(tapIndex) {
				let that = this;
				if (tapIndex == 0) {
					let img = that.head_img || that.thumb;
					uni.navigateTo({
						url: '/pages/user/user/avatar-cropping/index?rectHeight=200&rectWidth=200&fileType=jpg&myImgUrl=' +
							img,
						animationDuration: 0,
					});
				} else if (tapIndex == 1) {
					uni.chooseImage({
						count: 1,
						sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有
						success: (res) => {
							// 跳转到图片裁切页面
							uni.navigateTo({
								url: '/pages/user/user/avatar-cropping/index?rectHeight=200&rectWidth=200&fileType=jpg&myImgUrl=' +
									res.tempFilePaths[0],
								animationDuration: 0,
							});
						},
					});
				} else {
					uni.chooseImage({
						count: 1,
						sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ["album"], // 可以指定来源是相册还是相机，默认二者都有
						success: (res) => {
							// 跳转到图片裁切页面
							uni.navigateTo({
								url: `/pages/user/user/avatar-cropping/index?rectHeight=200&rectWidth=200&fileType=jpg&myImgUrl=${res.tempFilePaths[0]}`,
								animationDuration: 0,
							});
						},
					});
				}
				this.closeImg('headerimg');
			},
			// 表单提交
			formSubmit: function(e) {
				if (this.isLoading) return;

				if (timer) {
					clearTimeout(timer);
				}
				timer = setTimeout(() => {
					var formData = e.detail.value;

					// 添加头像
					formData.head_img = this.head_img;

					// 处理生日字段
					formData.birthday =
						formData.birthday.indexOf(this.i18n["选择"]) != -1 ? "" : formData.birthday;

					// 所在地
					formData.address = this.name.indexOf(this.i18n["选择"]) != -1 ? "" : this.name;
					formData.address_code = this.defaultVal;

					// 添加用户ID
					formData.user_id = this.userInfo.id ? this.userInfo.id : "";

					// 进行表单验证操作
					let validateRes = this.doValidate(formData);
					if (validateRes) {
						this.$message.info(validateRes);
						return;
					}

					this.isLoading = true;
					this.$api
						.post(global.apiUrls.editUserinfo, formData)
						.then((res) => {
							// setTimeout(() => {
							//   this.isLoading = false;
							// }, 500)
							if (res.data.code == 1) {
								this.isLoading = false;
								// 更新本地缓存
								uni.setStorageSync("USER_INFO", res.data.data.userinfo);

								// 更新global
								global.userInfo = res.data.data.userinfo;
								this.$message.info(this.i18n["修改成功"]);
								setTimeout(() => {
									uni.navigateBack();
								}, 500);
							}
						})
						.catch((err) => {
							this.isLoading = false;
							console.log(err);
						});
				}, 300);
			},

			// 进行表单字段值校验
			doValidate(formData) {
				console.log(formData);

				// 昵称
				if (!formData.user_nickname) {
					return this.i18n["请输入您的用户昵称"];
				}

				if (formData.user_nickname.length > 10) {
					return this.i18n["请检查您的昵称(最多10个字符)"];
				}

				// 生日
				if (!formData.birthday) {
					return this.i18n["请选择您的生日"];
				}

				return "";
			},

			/**
			 * @description 上传用户头像
			 */
			uploadUserImg(blob) {
				uni.showLoading();
				let _this = this;
				// 开始上传
				new UploadImage([blob], {
					complete: function(res) {
						console.log(res);
						uni.hideLoading();
						if (res.length) {
							_this.head_img = res[0].path;
							var formData = {
								head_img: res[0].id,
							};
							_this.$api
								.post(global.apiUrls.editUserinfo, formData)
								.then((res) => {
									if (res.data.code == 1) {
										// 更新本地缓存
										uni.setStorageSync("USER_INFO", res.data.data.userinfo);
										_this.$store.commit('updateUserInfo', res.data.data.userinfo);
										// 更新global
										global.userInfo = res.data.data.userinfo;
									}
								});
						}
					},
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
	}

	.grace-body {
		min-height: 100vh;
		background-color: #fff;
	}

	.head_list {
		background: #fff;
		padding: 20rpx 0;
		height: 152rpx;
		position: relative;

		&::after {
			content: "";
			position: absolute;
			bottom: 0;
			left: 32rpx;
			width: 100%;
			height: 1px;
			background: #ddd;
			transform: scaleY(0.5);
		}
	}

	.footer {
		position: fixed;
		left: 0rpx;
		bottom: 0rpx;
		// width: 100%;
		height: 88rpx;
		left: 32rpx;
		right: 32rpx;
		border-radius: 110rpx;
		bottom: calc(32rpx + constant(safe-area-inset-bottom));
		bottom: calc(32rpx + env(safe-area-inset-bottom));
	}

	.cu-list.menu {
		margin-top: 0;
	}

	.picker {
		background: #00b26a;
		width: 100%;
		line-height: 40px;
	}

	.address {
		display: inline-block;
		width: 110rpx;
	}

	.cu-item.arrow::before {
		color: #bfbfbf !important;
	}

	.cu-list.menu>.cu-item {
		height: 110rpx;
	}

	.address-select {
		// display: inline-block;
		width: 400rpx;
		// overflow: hidden;
		// white-space: nowrap;
		// text-overflow: ellipsis;
	}

	.content .title {
		display: inline-block;
		width: 160rpx;
		min-width: 160rpx;
	}

	.cu-list.menu-avatar>.cu-item:after,
	.cu-list.menu>.cu-item:after {
		left: 32rpx;
	}

	.header-popup {
		.height-20 {
			height: 20rpx;
			background: #f8f8f8;
		}

		.header-100 {
			height: 100rpx;
			line-height: 100rpx;
		}
	}

	/deep/ .sex-wrap .w-picker-view {
		height: 228rpx;
	}

	/deep/ .birthday-wrap uni-picker-view .uni-picker-view-wrapper {
		padding: 0 80rpx;
	}

	.solid-bottom {
		&::after {
			position: absolute;
			top: 0;
			left: 32rpx;
			box-sizing: border-box;
			width: 200%;
			height: 200%;
			border-bottom: 1rpx solid #ddd !important;
			border-radius: inherit;
			content: " ";
			-webkit-transform: scale(.5);
			transform: scale(.5);
			-webkit-transform-origin: 0 0;
			transform-origin: 0 0;
			pointer-events: none;
		}
	}
</style>